<?php

namespace app\api\controller;

use app\api\model\Notice;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Mini;
use app\common\library\Sms;
use app\common\model\MoneyLog;
use app\common\model\order\Pay;
use app\common\model\ScoreLog;
use fast\Random;
use Tencent\TLSSigAPIv2;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'mini_code', 'bind_mobile', 'get_token','iduser'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['userinfo' => $this->auth->getUserinfo()]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];


            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /*
     * 小程序获取openid
     * */
    public function mini_code()
    {
        $code = $this->request->param('code', null);
        if (is_null($code)) {
            $this->error("参数有误");
        }

        try {
            $app = Mini::app();
            $response = $app->auth->session($code);
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }

        if (!array_key_exists("errcode", $response)) {
            $this->success("成功", ['session_key' => $response['session_key'], 'userinfo' => [
                'id' => 0, 'username', 'nickname', 'mobile', 'avatar', 'money', 'score', 'group_id', 'anchor_status', 'order_ing', 'board_switch', 'exit_switch', 'up_switch', "openid" => $response['openid'],
            ]]);
        }
        switch ($response['errcode']) {
            case 40029:
                $errmsg = "code无效";
                break;
            case 45011:
                $errmsg = "API调用太频繁，请稍候再试";
                break;
            case 40226:
                $errmsg = "高风险等级用户，小程序登录拦截";
                break;
            case -1:
                $errmsg = "系统繁忙";
                break;
            default:
                $errmsg = "其他错误";
                break;
        }
        $this->error($errmsg);
    }

    /*
     * 小程序登录注册
     * */
    public function bind_mobile()
    {
        $iv = $this->request->param("iv");
        $session_key = $this->request->param("session_key");
        $encryptedData = $this->request->param("encryptedData");
        $open_id = $this->request->param('openid');
        if (!$iv || !$session_key || !$encryptedData || !$open_id) {
            $this->error("参数有误");
        }
        $app = Mini::app();
        $response = $app->encryptor->decryptData($session_key, $iv, $encryptedData);//解密信息
        if (!array_key_exists("errcode", $response)) {
            $user = \app\common\model\User::get(['openid' => $open_id]);
            if ($user) {
                $ret = $this->auth->direct($user['id']);
            } else {
                $ret = $this->auth->register($response['phoneNumber'], Random::build(), "", $response['phoneNumber'], ['openid' => $open_id]);
            }
            if (!$ret) {
                $this->error($this->auth->getError());
            }
            $this->success("成功", ['userinfo' => $this->auth->getUserinfo()]);
        }
        switch ($response['errcode']) {
            case 40029:
                $errmsg = "code无效";
                break;
            case -1:
                $errmsg = "系统繁忙";
                break;
            default:
                $errmsg = "其他错误";
                break;
        }
        $this->error($errmsg);
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {

//        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
//        $ret = Sms::check($mobile, $code, 'register');
//        if (!$ret) {
//            $this->error(__('Captcha is incorrect'));
//        }
        $ret = $this->auth->register($mobile, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio', "");
        $avatar = $this->request->post('avatar', "", 'trim,strip_tags,htmlspecialchars');
        $gender = $this->request->post('gender');
        $order_begin_notice = $this->request->post('order_begin_notice');
        $up_notice = $this->request->post('up_notice');
        if ($mobile) {
            $exists = \app\common\model\User::where('mobile', $mobile)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Mobile already exists'));
            }
            $user->mobile = $mobile;
        }
        if ($nickname) {
//            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
//            if ($exists) {
//                $this->error(__('Nickname already exists'));
//            }
            $user->nickname = $nickname;
        }
        if ($gender) {
            $user->gender = $gender;
        }
        if ($bio) {
            $user->bio = $bio;
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        if ($order_begin_notice) {
            $user->order_begin_notice = $order_begin_notice;
        }
        if ($up_notice) {
            $user->up_notice = $up_notice;
        }

        $user->save();
        $this->success("修改成功");
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function consumption_record()
    {
        $params = $this->request->param();
        $msg = "消费记录";
        MoneyLog::where('user_id');
        switch ($params['type']) {
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                break;
            default:
                $this->success($msg, null);
                break;
        }
    }

    //用户的金币消费记录
    public function consume_log()
    {
        $user = $this->auth->getUser();
        $pagesize = $this->request->post('pagesize', 10);
        $msg = "消费记录";
        $userMoney = MoneyLog::where('user_id', $user['id'])->where('type', 'in', [1, 2])->order('createtime desc')->paginate($pagesize)->each(function ($v) {
            if ($v['type'] == 1) {
                $order_place = Db::name('order_place')->where('id', $v['memo'])->find();
//                $v['num'] = $order_place['num'];
                $v['anchor_nickname'] = Db::name('user')->where('id', $order_place['anchor_id'])->value('nickname');

            } elseif ($v['type'] == 2) {
                $order_gen = Db::name('order_gen')->where('id', $v['memo'])->find();
//                $v['num'] = $order_gen['num'];
                $v['anchor_nickname'] = Db::name('user')->where('id', $order_gen['anchor_id'])->value('nickname');
            }
            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            return $v;
        });
        //消除红点
        MoneyLog::where('user_id',$user['id'])->where('type','in',[1,2])->update(['red_status'=>1]);
        //修改主播信息
        Db::name('user')->where('id',$user['id'])->update(['consumptionlog_red_status'=>1]);
        $this->success($msg, $userMoney);

    }

    //用户守护值记录
    public function user_socre_log()
    {
        $user = $this->auth->getUser();
        $pagesize = $this->request->post('pagesize', 10);
        $msg = "守护值记录";
        $userMoney = ScoreLog::where('user_id', $user['id'])->where('type', 'in', [1, 2])->order('createtime desc')->paginate($pagesize)->each(function ($v) {
            if ($v['type'] == 1) {
                $order_place_pro = Db::name('order_place_pro')->where('id', $v['memo'])->find();
                $v['anchor_nickname'] = Db::name('user')->where('id', $order_place_pro['anchor_id'])->value('nickname');

            } elseif ($v['type'] == 2) {
                $order_gen = Db::name('order_gen')->where('id', $v['memo'])->find();
                $v['anchor_nickname'] = Db::name('user')->where('id', $order_gen['anchor_id'])->value('nickname');
            }
            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            return $v;
        });
        //消除红点
        ScoreLog::where('user_id',$user['id'])->update(['red_status'=>1]);
        //修改主播信息
        Db::name('user')->where('id',$user['id'])->update(['scorelog_red_status'=>1]);
        $this->success($msg, $userMoney);

    }

    //用户充值记录
    public function user_pay_log()
    {
        $user = $this->auth->getUser();
        $pagesize = $this->request->post('pagesize', 10);
        $msg = "充值记录";
        $data = Pay::where('user_id', $user['id'])->where('status', 1)->order('createtime desc')->paginate($pagesize)->each(function ($v) {
            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            $v['pay_time'] = date('Y-m-d H:i:s', $v['pay_time']);
            $money = $v['money'];
            $v['content'] = "充值$money" . "金币";
            return $v;
        });
        //主播金币记录消除红点
        MoneyLog::where('user_id',$user['id'])->where('type',0)->update(['red_status'=>1]);
        //修改主播信息
        Db::name('user')->where('id',$user['id'])->update(['paylog_red_status'=>1]);
        $this->success($msg, $data);

    }

    //用户查看我的系统通知
    public function user_notice()
    {
        $user = $this->auth->getUser();
        $pagesize = $this->request->post('pagesize', 10);
        $date = Notice::where('user_id', $user['id'])
            ->order('createtime desc')
            ->paginate($pagesize)
            ->each(function ($orderdate) {
                $orderdate['createtime'] = date("Y-m-d H:i:s", $orderdate['createtime']);
                return $orderdate;
            });
        $data['data'] = $date;

        $is_show = Notice::where('user_id', $user['id'])->where('red_status', 0)->find();
        if ($is_show) {
            $data['is_show'] = 1;
        } else {
            $data['is_show'] = 0;
        }
        $this->success('成功', $data);
    }

    //用户查看我的系统通知详情
    public function user_notice_ing()
    {
        $user = $this->auth->getUser();
        $id = $this->request->post('id');
        $date = Notice::where('user_id', $user['id'])
            ->where('id', $id)
            ->find();
        $date['createtime'] = date("Y-m-d H:i:s", $date['createtime']);
        $this->success('成功', $date);
    }

    public function genUserSig()
    {
        $api = new TLSSigAPIv2(1400800289, "11076590fffcd4c490802d5c5d2bc34e4ad5afd0b5d9c0382d568c3d1c0e7646");
        $sig = $api->genUserSig($this->auth->id);
        $this->success("成功", $sig);
    }

    public function user_opinion()
    {
        $content = $this->request->post('content');
        $user = $this->auth->getUser();
        $data = [
            'content' => $content,
            'user_id' => $user['id'],
            'user_mobile' => $user['mobile'],
            'createtime' => time(),
            'updatetime' => time()
        ];
        Db::name('user_opinion')->insert($data);
        $this->success('成功');
    }

    //用户访问去红点
    public function red_end()
    {
        $user = $this->auth->getUser();
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        if ($status == 1) { // 系统消息
            $update = Db::name('notice')->where('id', $id)->update(['red_status' => 1]);
        } elseif ($status == 2) { //订单消息
            $update = Db::name('order_news')->where('user_id', $user['id'])->update(['red_status' => 1]);
        }
        $this->success('成功');
    }

    public function get_token()
    {
        $coerce = $this->request->param('coerce', 0);
        $app = Mini::app();
        if ($coerce) {
            $token = $app->access_token->getToken();
            cache('access_token_three', $token, ['expire' => 7200]);
        } else {
            if (cache('access_token_three')) {
                $token = cache('access_token_three');
            } else {
                $token = $app->access_token->getToken();
                cache('access_token_three', $token, ['expire' => 7200]);
            }
        }
        $this->success("token", $token);
    }

    public function iduser(){
        $id = $this->request->param('id', 0);
        $user = Db::name('user')->where('id',$id)->find();
        $this->success("token", $user);
    }
}
